package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

const RenameCmd = "rename"

const RenameUsage = `
该命令用于[批量]修改文件名
rename 	-p dir -r Regex -t replaceStr -i [false]
    -p 路径         可以是目录路径；也可以是文件路径
    -r 正则表达式    匹配路径中的字符串的正则
    -t 替换字符串    替换正则表达式匹配到的字符串
    -i 是否写入      默认为false，只在屏幕打印，当为true时，执行操作
`

type RenameCommond struct {
	flagset 	*flag.FlagSet
	path 		string
	regex 		string
	target 		string
	input		bool
}


func (re *RenameCommond)Register(){
	re.flagset = flag.NewFlagSet(RenameCmd, flag.ExitOnError)
	re.flagset.StringVar(&(re.path),"p", "./", RenameUsage)
	re.flagset.StringVar(&(re.regex),"r", "", RenameUsage)
	re.flagset.StringVar(&(re.target),"t", "", RenameUsage)
	re.flagset.BoolVar(&(re.input),"i",false, RenameUsage)
}

func (re *RenameCommond)Run(Para []string ){
	//fmt.Println(Para)
	//解析
	err := re.flagset.Parse(Para)
	CheckError(err)
	if re.flagset.Parsed(){
		//首先判断path是否是dir路径
		formatPath := NewRegex("\\\\")
		re.path =  formatPath.ReplaceAllString(re.path, "/")
		isExist, isDir := IsExistAndIsDir(re.path)
		if !isExist {
			PrintMsg(fmt.Sprintf("path %s is not exit",re.path))
			os.Exit(1)
		}
		if len(re.regex) == 0 {
			PrintMsg("Invalid input -r is nil")
			PrintMsg(RenameUsage)
			os.Exit(1)
		}
		if len(re.target) == 0 {
			PrintMsg("Invalid input -t is nil")
			PrintMsg(RenameUsage)
			os.Exit(1)
		}
		//PrintMsg(fmt.Sprintf("%v %v %v %v",re.path, re.target, re.regex, re.input))
		//获取正则规则
		regex := NewRegex(re.regex)
		if isDir {
			//读取文件夹
			files, err := ioutil.ReadDir(re.path)
			CheckError(err)
			for _, v := range files {
				if v.IsDir() || !regex.MatchString(v.Name()){
					continue
				}
				rename := regex.ReplaceAllString(v.Name(),re.target)
				PrintMsg(regex.ReplaceAllString(rename,re.target))
				if re.input {
					err  = os.Rename(re.path + "/" + v.Name(), re.path + "/" + rename)
					CheckError(err)
				}
			}
		}else{
			//获取文件名
			index := strings.LastIndex(re.path, "/")
			fileName := (re.path)[index:]
			Path := (re.path)[:index]
			reFileName :=  regex.ReplaceAllString(fileName,re.target)
			PrintMsg(Path + reFileName)
			if re.input {
				err = os.Rename(Path + fileName , Path + reFileName )
				CheckError(err)
			}

		}
	}
}